package com.business.system.action;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import net.sf.rose.jdbc.DBUtils;
import net.sf.rose.jdbc.PageBean;
import net.sf.rose.jdbc.service.Service;
import net.sf.rose.util.DateFormat;
import net.sf.rose.web.utils.WebUtils;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.business.system.bean.SettleLogBean;
import com.business.system.util.DBTools;
import com.business.system.util.PageUtil;

/**
 * @author: xudy
 * @date: 2018/04/15 16:35
 * @description:结算管理
 */
@RestController
@RequestMapping("settle")
public class SettleAction extends BaseAction {
	@RequestMapping("getSettleList.do")
	public PageBean getSettleList(Service service, HttpServletRequest request) {
		PageBean page = PageUtil.page(request);
		StringBuilder sql = new StringBuilder();
		sql.append("select t1.*,t2.USER_NAME from settle_log t1 left join wx_user t2 on t1.USER_ID=t2.ID where 1=1");
		Map<String, Object> params = WebUtils.getRequestData(request);
        List<Object> condition = new ArrayList<>();
        if(params.containsKey("beginTime")){
            sql.append(" and t1.STATIC_TIME>=?");
            condition.add(params.get("beginTime"));
        }
        if(params.containsKey("endTime")){
            sql.append(" and t1.STATIC_TIME<=?");
            condition.add(params.get("endTime"));
        }
        if(params.containsKey("state") && !"0".equals(params.get("state"))){
            sql.append(" and t1.STATE=?");
            condition.add(params.get("state"));
        }
        if(params.containsKey("content")){
            sql.append(" and t2.user_name like '%"+params.get("content")+"%'");
        }
        DBTools.getDataList(service, sql.toString(), page,condition);
		return page;
	}

    /**
     * 单条记录保存
     * @param service
     * @param request
     * @return
     */
    @RequestMapping("updateSettleLog.do")
	public Boolean updateSettleLog(Service service,HttpServletRequest request){
        Map<String, Object> params = WebUtils.getRequestData(request);
        SettleLogBean log = DBUtils.getBean(service,SettleLogBean.class,params.get("ID").toString());
        log.setRealFee(Double.parseDouble(params.get("REAL_FEE").toString()));
        log.setState(2);//已结算
        return DBUtils.update(service,log)>0;
    }

    @RequestMapping("batchUpdateSettleLog.do")
    public Boolean batchUpdateSettleLog(Service service,HttpServletRequest request, String ids){
        StringBuilder sql = new StringBuilder();
        sql.append("update settle_log set state=?,update_time=?,REAL_FEE=TOTAL_FEE  where id in ("+ids+")");
        int j = DBTools.updateSql(service,sql.toString(),2, DateFormat.getTimestamp());
        return (j==ids.split(",").length);
    }



    /**
     * @Description:月度结算
     * @Author: zhangqiang
     * @Date: 9:29 2018/4/20
     * @Desc:
     * 销售毛利，back_fee_log中已结算的订单(order)的总额；
     * 加盟费,代理费，back_fee_log中已结算的申请(apply)的加盟费，代理费
     * 代理返利，back_fee_log中已结算的代理返利
     * 推荐返利，back_fee_log中已结算的推荐返利
     *
     */
    @RequestMapping("getMonthSettle.do")
    public List<Map<String,Object>> getMonthSettle(Service service, HttpServletRequest request){
        Map<String, Object> params = WebUtils.getRequestData(request);
        List<Object> condition = new ArrayList<>();

        String  area = params.get("area").toString();

        //销售毛利
        StringBuilder sql = new StringBuilder();
        sql.append("SELECT " +
                " SUM(t3.COUNTS*t3.SALE_PRICE) AS sale_count," +
                "SUM(t1.BACK_FEE) AS dl_fee," +
                "t5.AREA,t6.ID as 'BRAND_ID',t6.BRAND_NAME " +
                "FROM " +
                " back_fee_log t1 " +
                "LEFT JOIN goods_orders t2 ON t1.RESOURCE_ID = t2.ID " +
                "LEFT JOIN order_goods t3 ON t2.ID = t3.ORDERS_ID " +
                "LEFT JOIN goods t4 on t4.ID= t3.GOODS_ID " +
                "LEFT JOIN user_brand t5 on t1.FROM_USER_ID = t5.USER_ID " +
                "LEFT JOIN brand t6 on t4.BRAND_ID = t6.ID " +
                "WHERE " +
                " 1 = 1 " +
                "AND t1.TYPE = 1 " +
                "AND t1.STATE=2 " +
                "AND t2.ID <>'' AND t3.ID <>'' AND t4.ID <> '' AND t5.ID <>'' " );

        if(params.containsKey("month") ){
            sql.append(" and left(t1.CREATE_TIME,7) =?");
            condition.add(params.get("month").toString());
        }

        if(params.containsKey("brand")){
            sql.append(" and t6.ID = ?");
            condition.add(params.get("brand"));
        }

        //TODO
        switch (area){

            //省级
            case "1":
                sql.append(" GROUP BY t5.AREA,t6.ID ");

                break;
            //市级
            case "2":
                sql.append(" GROUP BY t5.AREA,t6.ID ");
                break;
            //县级
            case "3":
                sql.append(" GROUP BY t5.AREA,t6.ID ");
                break;
            default:
                break;
        }

        sql.append(" ORDER BY t5.AREA  ");
        List<Map<String,Object>> sale_count = DBTools.getDataList(service, sql.toString(),condition);


        //加盟费
        sql= new StringBuilder();
        condition = new ArrayList<>();

        sql.append("SELECT " +
                " SUM(case t2.TYPE when '1' then t2.APPLY_FEE END) as dl_count, " +
                " SUM(case t2.TYPE when '2' then t2.APPLY_FEE END) as jm_count, " +
                " SUM(t1.BACK_FEE) AS tj_fee," +
                " t4.BRAND_NAME,t3.* FROM " +
                " back_fee_log t1 " +
                "LEFT JOIN apply t2 ON t1.RESOURCE_ID = t2.ID " +
                "LEFT JOIN user_brand t3 on t1.FROM_USER_ID = t3.USER_ID " +
                "LEFT JOIN brand t4 on t3.BRAND_ID = t4.ID " +
                "where t1.STATE=2 AND t1.TYPE =2 AND t2.ID <>'' AND t3.ID <>'' AND t4.ID <> '' ");


        if(params.containsKey("month") ){
            sql.append(" and left(t2.CREATE_TIME,7) =?");
            condition.add(params.get("month").toString());
        }

        if(params.containsKey("brand")){
            sql.append(" and t4.ID = ?");
            condition.add(params.get("brand"));
        }

        //TODO
        sql.append(" GROUP BY t3.AREA,t3.BRAND_ID ORDER BY t3.AREA ");
        List<Map<String,Object>> fee_count = DBTools.getDataList(service, sql.toString(),condition);


        List<Map<String,Object>> final_list = new ArrayList<>();
        if(sale_count.size()>=fee_count.size()){

            for(Map<String,Object> map_sale:sale_count) {
                Map<String,Object> temp_map = new HashMap<>();
                temp_map.putAll(map_sale);

                if(fee_count.size()==0){

                    temp_map.put("dl_count",0);
                    temp_map.put("jm_count",0);
                    temp_map.put("tj_fee",0);
                    double total_count= Double.parseDouble(temp_map.get("sale_count").toString())+
                            Double.parseDouble(temp_map.get("dl_count").toString())+
                            Double.parseDouble(temp_map.get("jm_count").toString())-
                            Double.parseDouble(temp_map.get("tj_fee").toString())-
                            Double.parseDouble(temp_map.get("dl_fee").toString());

                    temp_map.put("total_count",total_count);
                    final_list.add(temp_map);
                }
                else{
                    for (Map<String, Object> map_fee : fee_count) {
                        if((map_sale.get("AREA").equals(map_fee.get("AREA"))) & (map_sale.get("BRAND_ID").equals(map_fee.get("BRAND_ID")))){
                            temp_map.put("dl_count",map_fee.get("dl_count"));
                            temp_map.put("jm_count",map_fee.get("jm_count"));
                            temp_map.put("tj_fee",map_fee.get("tj_fee"));
                        }
                        else{
                            temp_map.put("dl_count",0);
                            temp_map.put("jm_count",0);
                            temp_map.put("tj_fee",0);
                        }

                        double total_count= Double.parseDouble(temp_map.get("sale_count").toString())+
                                Double.parseDouble(temp_map.get("dl_count").toString())+
                                Double.parseDouble(temp_map.get("jm_count").toString())-
                                Double.parseDouble(temp_map.get("tj_fee").toString())-
                                Double.parseDouble(temp_map.get("dl_fee").toString());

                        temp_map.put("total_count",total_count);
                        final_list.add(temp_map);
                    }
                }


            }


        }
        else{

            for(Map<String,Object> map_fee:fee_count) {
                Map<String,Object> temp_map = new HashMap<>();
                temp_map.putAll(map_fee);

                if(sale_count.size()==0){
                    temp_map.put("sale_count",0);
                    temp_map.put("dl_fee",0);
                    double total_count= Double.parseDouble(temp_map.get("sale_count").toString())+
                            Double.parseDouble(temp_map.get("dl_count").toString())+
                            Double.parseDouble(temp_map.get("jm_count").toString())-
                            Double.parseDouble(temp_map.get("tj_fee").toString())-
                            Double.parseDouble(temp_map.get("dl_fee").toString());

                    temp_map.put("total_count",total_count);
                    final_list.add(temp_map);
                }
                else{
                    for (Map<String, Object> map_sale : sale_count) {
                        if((map_sale.get("AREA").equals(map_fee.get("AREA"))) & (map_sale.get("BRAND_ID").equals(map_fee.get("BRAND_ID")))){

                            temp_map.put("sale_count",map_sale.get("sale_count"));
                            temp_map.put("dl_fee",map_sale.get("dl_fee"));
                        }
                        else{
                            temp_map.put("sale_count",0);
                            temp_map.put("dl_fee",0);
                        }
                        double total_count= Double.parseDouble(temp_map.get("sale_count").toString())+
                                Double.parseDouble(temp_map.get("dl_count").toString())+
                                Double.parseDouble(temp_map.get("jm_count").toString())-
                                Double.parseDouble(temp_map.get("tj_fee").toString())-
                                Double.parseDouble(temp_map.get("dl_fee").toString());

                        temp_map.put("total_count",total_count);
                        final_list.add(temp_map);
                    }
                }

                }

            }

        //保留两位小数
        DecimalFormat df = new DecimalFormat("#.00");

        Map<String,Integer> key_map = new HashMap<>();
        List<Map<String,Object>> final_list2 = new ArrayList<>();

        for (Map<String, Object> final_map : final_list) {
            final_map.put("sale_count",Double.parseDouble(final_map.get("sale_count").toString())==0?0.00:df.format(Double.parseDouble(final_map.get("sale_count").toString())));
            final_map.put("jm_count",Double.parseDouble(final_map.get("jm_count").toString())==0?0.00:df.format(Double.parseDouble(final_map.get("jm_count").toString())));
            final_map.put("dl_count",Double.parseDouble(final_map.get("dl_count").toString())==0?0.00:df.format(Double.parseDouble(final_map.get("dl_count").toString())));
            final_map.put("dl_fee",Double.parseDouble(final_map.get("dl_fee").toString())==0?0.00:df.format(Double.parseDouble(final_map.get("dl_fee").toString())));
            final_map.put("tj_fee",Double.parseDouble(final_map.get("tj_fee").toString())==0?0.00:df.format(Double.parseDouble(final_map.get("tj_fee").toString())));
            final_map.put("total_count",Double.parseDouble(final_map.get("total_count").toString())==0?0.00:df.format(Double.parseDouble(final_map.get("total_count").toString())));

//            final_list2.add(final_map);
//            final_list2.add(final_map);
//            final_list2.add(final_map);
//            final_list2.add(final_map);
//            final_list2.add(final_map);

            String temp_key =final_map.get("AREA").toString();

            if(key_map.containsKey(temp_key)){
                key_map.put(temp_key,key_map.get(temp_key)+1);
            }
            else{
                key_map.put(temp_key,1);
            }

        }


        //前台合并
        for (Map<String, Object> map : final_list) {

            Map<String, Object> temp_map = new HashMap<>();
            temp_map.putAll(map);

            String temp_key =map.get("AREA").toString();
            if(key_map.containsKey(temp_key)){
                temp_map.put("colspan",key_map.get(temp_key));
                key_map.put(temp_key,0);
            }


            final_list2.add(temp_map);
        }

        return final_list2;
    }



}